/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package autopecas.Dados;

import autopecas.ClasseBasica.NotaFiscal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 *
 * @author NeGo
 */
public class DadosNotaFiscal {
    
    private DadosConexao bdConn;
    private PreparedStatement stmt;
    private String sql;
    private DateFormat dateFormat;
    private Date date;
    private ResultSet rs;
    
    public DadosNotaFiscal(){
        
        bdConn = new DadosConexao();
        dateFormat = new SimpleDateFormat("yyyyMMdd");
        date = new Date();
    }
    
    /**
     * Recebe informações da nota fiscal pra persistência
     * @param notaFis Informações da nota fiscal pra persistência
     * @throws java.sql.SQLException - erros retornados do banco
     */
    public void registrarNf(NotaFiscal notaFis) throws SQLException{
      sql = "INSERT INTO NOTAFISCAL (CODFUNC,VALORNF,CPFCLI,DATENF) VALUES (?,?,?,?)";
      stmt = bdConn.conectarMysql().prepareStatement(sql);
      stmt.setInt(1, notaFis.getFuncionario().getMatricula());
      stmt.setDouble(2, notaFis.getValorNf());
      stmt.setLong(3, notaFis.getCliente().getCpf());
      stmt.setInt(4, Integer.parseInt(dateFormat.format(date)));
      stmt.execute();
    }
    
    public ArrayList<NotaFiscal> listarNfs(int Codfun) throws SQLException{
        ArrayList<NotaFiscal> retorno = new ArrayList<>();
        sql = "SELECT * FROM NOTAFISCAL WHERE CODFUN = ?";
        stmt = bdConn.conectarMysql().prepareStatement(sql);
        stmt.setInt(1, Codfun);
        rs = stmt.executeQuery();
        while(rs.next()){
            NotaFiscal nfRetorno =  new NotaFiscal();
            nfRetorno.setCodigoNf(rs.getInt("CODNOTAFIS"));
            nfRetorno.setValorNf(rs.getDouble("ValorNF"));
            sql = "SELECT * FROM FUNCIONARIO WHERE CODFUN = ?";
            stmt = bdConn.conectarMysql().prepareStatement(sql);
            stmt.setInt(1, rs.getInt("CodFunc"));
            ResultSet rsFunc = stmt.executeQuery();
            nfRetorno.getFuncionario().setMatricula(rsFunc.getInt("matricula"));
            nfRetorno.getFuncionario().setNomeFuncionario(rs.getString("nome"));
            sql = "SELECT * FROM CLIENTE WHERE CODCLI = ?";
            stmt = bdConn.conectarMysql().prepareStatement(sql);
            stmt.setInt(1, rs.getInt("CpfCli"));
            ResultSet rsCli = stmt.executeQuery();
            nfRetorno.getCliente().setCpf(rsCli.getInt("cpf"));
            nfRetorno.getCliente().setNome(rsCli.getString("nome"));
            
        }
        return retorno;
    }
    
}
